<template>
  <view class="page-all">
    <Header :leftIconSize="20" :title="title" bgColor="#fff"></Header>
    <view class="radius-contain">
      <uv-form ref="rForm" :model="form" :rules="rules" labelPosition="left">
        <uv-form-item borderBottom prop="taskOrgList" @click="toSelectSchool">
          <template #label>
            <div class="requireStar">选择学校</div>
          </template>
          <uv-input v-model="form.school" border="none" disabled="true" disabledColor="#fff" inputAlign="right"
                    placeholder="请选择检查学校" placeholderClass="placeholder-color"></uv-input>
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        <uv-form-item borderBottom label="" prop="targetName" @click="toSelectIndex">
          <template #label>
            <div class="requireStar">选择指标</div>
          </template>
          <uv-input v-model="form.targetName" border="none" disabled="true" disabledColor="#fff" inputAlign="right"
                    placeholder="请选择检查指标" placeholderClass="placeholder-color"></uv-input>
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        <uv-form-item borderBottom label="" prop="date" @click="showCalendar">
          <template #label>
            <div class="requireStar">选择日期</div>
          </template>
          <uv-input v-model="form.date" border="none" disabled="true" disabledColor="#fff" inputAlign="right"
                    placeholder="请选择检查日期" placeholderClass="placeholder-color"></uv-input>
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        <uv-form-item borderBottom label="" @click="showScreen">
          <template #label>
            <div class="normal">检查内容</div>
          </template>
          <uv-input v-model="form.content" border="none" disabled="true" disabledColor="#fff" inputAlign="right"
                    placeholder="请输入检查内容" placeholderClass="placeholder-color"></uv-input>
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        <uv-form-item borderBottom label="" @click="">
          <template #label>
            <div class="normal">是否立即通知学校</div>
          </template>
          <uv-input border="none" disabled="true" disabledColor="#fff" inputAlign="right"
                    placeholderClass="placeholder-color"></uv-input>
          <template v-slot:right>
            <view class="switch-text">
              <view>{{ form.notice ? '是' : '否' }}</view>
              <uv-switch v-model="form.notice" @change="changeNotice"></uv-switch>
            </view>
          </template>
        </uv-form-item>
      </uv-form>
    </view>


    <uv-calendars ref="calendar" allowSameDay="true" mode="range" @confirm="dateConfirm"></uv-calendars>
    <view class="check-bottom-box" @click.stop>
      <button :disabled="loading" class="sure-button" @click.stop="submit()">确认</button>
    </view>

    <uv-popup ref="popup" :closeable="true" @change="change">
      <view class="popup-title">检查内容</view>
      <view class="popup-content">
        <view class="info textAreaBox">
          <uv-textarea v-model="content" :fixed="true" count cursorSpacing="50" height="100" maxlength="140"
                       placeholder="请输入内容"></uv-textarea>
          <view class="fontCount" @click="showSpeech">
            <image :src="imgMinioPath + '/law/yuyin.png'"></image>
          </view>
        </view>
        <!--                <textarea v-model="content" height="100" placeholder="请输入检查内容" class="text-area"></textarea>-->
        <view class="bottom-box" @click.stop>
          <button class="sure-button" @click.stop="popupSubmit()">确认</button>
        </view>
      </view>
    </uv-popup>

    <uv-popup ref="refSpeech" mode="bottom" round="8" @change="change">
      <speech-recognition v-if="refSpeechShow" :maxlength="140" @getSpeeckInfo="getSpeeckInfo"></speech-recognition>
    </uv-popup>
  </view>
</template>

<script setup>
import {defineProps, getCurrentInstance, reactive, ref} from 'vue'
import supTaskAPI from "@/api/law/supTask/supTask";
import {onLoad, onReady, onShow,} from '@dcloudio/uni-app'
import config from "@/common/config";

const {proxy} = getCurrentInstance();
let imgMinioPath = ref(config.IMG_MINIO_PATH);
const props = defineProps({
  data: {
    type: Object,
    default: () => {
      return {};
    }
  },
  editFlag: {
    required: false,
    type: Boolean,
    default: false
  }
});

let userInfo = ref(uni.getStorageSync('userInfo').user);
let title = ref('创建任务');
let rules = {
  taskOrgList: [
    {
      validator: (rule, value, callback) => {
        //返回true表示校验通过，返回false表示不通过
        return value.length > 0;
      },
      message: '请选择检查学校',
      trigger: ['blur', 'change']
    }
  ],
  targetName: {
    required: true,
    message: '请选择指标',
    trigger: ['blur', 'change']
  },
  date: {
    required: true,
    message: '请选择日期',
    trigger: ['blur', 'change']
  },
}
let loading = ref(false);


let notice = ref(false);
let content = ref('');
const entryType = ref("2");
let form = reactive({
  schoolNum: 0,
  taskOrgList: [],
  content: '',
  entryType:'',
})
const rForm = ref('')
let canteenPicker = ref()
//选择检查日期
const calendar = ref()

function showCalendar() {
  calendar.value.open()
}

// 日期选择确认
function dateConfirm(e) {
  form.date = e.range.before + '~' + e.range.after;
  form.taskBeginDate = e.range.before;
  form.taskEndDate = e.range.after;
  rForm.value.validateField('date', err => {
    // 处理错误后的逻辑
  })
}

// 通知按钮
function changeNotice(e) {
  form.noticeFlag = e ? '1' : '0'
}

let popup = ref();

//显示筛选弹层
function showScreen() {
  popup.value.open('bottom');
}

function popupSubmit() {
  form.content = content.value
  popup.value.close();
}

onReady(() => {
  rForm.value.setRules(rules)
});

onLoad(async (e) => {
  if (e.data) {
    e.data = JSON.parse(decodeURIComponent(e.data))
  }
  if (e.editFlag) {
    title = ref('编辑任务');
    getData(e.data.id);
  } else {
    title = ref('创建任务');
  }
});
/** 获取数据 */
const getData = (id) => {
  proxy.http.get(supTaskAPI.entryQuery(id)).then(res => {
    if (res.code === 0) {
      Object.assign(form, res.data);
      form.school = form.taskOrgList.length + '所学校'
      form.date = `${form.taskBeginDate}~${form.taskEndDate}`
      form.notice = form.notice === '1' ? true : false
    } else {
      uni.showToast({title: res.msg, icon: 'none'});
    }
  })
};

onShow(() => {
  entryType.value=uni.getStorageSync('entryType')
  form.entryType=uni.getStorageSync('entryType');
  //接收选择学校传回的数据 data:{id,name}
  uni.$on('schoolData', function (data) {
    form.taskOrgList = data.map(function (obj) {
      return {schoolId: obj.id, schoolName: obj.name};
    });
    form.schoolId = data.map(function (obj) {
      return obj.id;
    }).join(',')
    form.schoolName = data.map(function (obj) {
      return obj.name;
    }).join(',')
    form.school = form.taskOrgList.length + '所学校'
    if (rForm.value != null) {
      rForm.value.validateField('taskOrgList', err => {
        // 处理错误后的逻辑
      })
    }
  })
  //接收选择指标传回的数据  data:{id,name}
  uni.$on('indexData', function (data) {
    form.targetId = data[0].id
    form.targetName = data[0].name
    if (rForm.value != null) {
      rForm.value.validateField('targetName', err => {
        // 处理错误后的逻辑
      })
    }
  })
})


//跳转到选择学校
function toSelectSchool() {
  uni.navigateTo({
    url: `/packageLawEnforcement/pages/createTask/selectSchool?list=${encodeURIComponent(JSON.stringify(form.taskOrgList))}`
  })
}

//跳转选择指标
function toSelectIndex() {
  uni.navigateTo({
    url: `/packageLawEnforcement/pages/createCheck/selectIndex?radiovalue=${form.targetId}`
  })
}

function submit() {
  loading.value = false;
  // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
  proxy.$refs["rForm"].validate().then(res => {
    if (props.editFlag) {
      update();
    } else {
      form.orgId = userInfo.value.id
      form.orgName = userInfo.value.nickName
      form.userId = userInfo.value.org.id
      form.userName = userInfo.value.org.orgName
      save();
    }
  }).catch(errors => {
  })
}

/** 添加功能 **/
let save = async () => {
  uni.showModal({
    title: '温馨提示',
    content: '确定添加该条数据？',
    success: async function (res) {
      if (res.confirm) {
        let res = await proxy.http.asyncPost(supTaskAPI.saveSupTask, form);
        if (res.code === 0) {
          await uni.showToast({icon: 'success', title: '创建成功', duration: 2000});
          loading.value = true;
          setTimeout(() => {
            goBack();
          }, 1000)
        } else {
          await uni.showToast({title: res.msg, icon: 'none'});
        }
      }
    }
  })
};

/** 编辑功能 **/
let update = async () => {
  uni.showModal({
    title: '温馨提示',
    content: '确定编辑该条数据？',
    success: async function (res) {
      if (res.confirm) {
        let res = await proxy.http.asyncPost(supTaskAPI.updateSupTask, form);
        if (res.code === 0) {
          await uni.showToast({icon: 'success', title: '编辑成功', duration: 2000});
          loading.value = true;
          setTimeout(() => {
            goBack();
          }, 1000)
        } else {
          await uni.showToast({title: res.msg, icon: 'none'});
        }
      }
    }
  })
};

/** 返回上一页 */
let goBack = async () => {
  uni.$emit("refresh", {});
  await uni.navigateBack();
};
const refSpeechShow = ref(false);
const change = (e) => {
  refSpeechShow.value = e.show
}
/** 语音输入 */
const refSpeech = ref();
const showSpeech = () => {
  refSpeech.value.open();
};

function getSpeeckInfo(val) {
  refSpeech.value.close();
  content.value += val;
}

</script>

<style lang="scss" scoped>
.textAreaBox {
  position: relative;

  ::v-deep .uv-textarea__field {
    text-align: left !important;
    padding: 20rpx 20rpx 50rpx !important;
  }
}

.fontCount {
  z-index: 99;
  position: absolute;
  bottom: 2px;
  right: 130rpx;
  color: #9e9e9e;
  font-size: 28rpx;
  display: flex;
  align-items: center;

  image {
    height: 50rpx;
    width: 50rpx;
  }
}

.switch-text {
  display: flex;
}


::v-deep .placeholder-color {
  color: rgba(0, 0, 0, 0.3);
  font-size: 32rpx;
}

::v-deep .requireStar {
  width: 30%;
}

::v-deep .requireStar:after {
  vertical-align: bottom; //加上星号会上下居中，不加会在上角展示
  content: ' *';
  color: rgba(255, 59, 48, 1);
  font-size: 100%;
}

::v-deep .normal {
  width: 30%;
  font-size: 32rpx;
}

::v-deep .normal:after {
  vertical-align: bottom; //加上星号会上下居中，不加会在上角展示
  color: rgba(255, 59, 48, 1);
  font-size: 100%;
}
</style>
